const express = require('express');
const { body, query, param, validationResult } = require('express-validator');
const multer = require('multer');
const path = require('path');
const { Course, User } = require('../models');
const { authenticate, authorize } = require('../middleware/auth');
const { AppError, ValidationError } = require('../middleware/errorHandler');
const config = require('../config/config');
const logger = require('../config/logger');

const router = express.Router();

// 文件上传配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = file.fieldname === 'coverImage' ? 'uploads/courses/covers' : 'uploads/courses/attachments';
    cb(null, path.join(process.cwd(), uploadPath));
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, `${file.fieldname}-${uniqueSuffix}${path.extname(file.originalname)}`);
  }
});

const upload = multer({
  storage,
  limits: {
    fileSize: config.upload.maxFileSize,
    files: 5
  },
  fileFilter: (req, file, cb) => {
    if (file.fieldname === 'coverImage') {
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
      if (allowedTypes.includes(file.mimetype)) {
        cb(null, true);
      } else {
        cb(new AppError('封面图片只允许上传图片文件', 400), false);
      }
    } else {
      // 附件允许更多文件类型
      const allowedTypes = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'text/plain',
        'application/zip',
        'application/x-rar-compressed'
      ];
      if (allowedTypes.includes(file.mimetype)) {
        cb(null, true);
      } else {
        cb(new AppError('不支持的附件文件类型', 400), false);
      }
    }
  }
});

// 验证规则
const createCourseValidation = [
  body('title')
    .notEmpty()
    .withMessage('课程标题不能为空')
    .isLength({ min: 1, max: 200 })
    .withMessage('课程标题长度必须在1-200个字符之间'),
  
  body('subtitle')
    .optional()
    .isLength({ max: 500 })
    .withMessage('课程副标题不能超过500个字符'),
  
  body('description')
    .optional()
    .isLength({ max: 2000 })
    .withMessage('课程描述不能超过2000个字符'),
  
  body('level')
    .isIn(['beginner', 'intermediate', 'advanced', 'expert'])
    .withMessage('课程难度级别无效'),
  
  body('price')
    .isDecimal({ decimal_digits: '0,2' })
    .withMessage('价格格式无效')
    .custom((value) => {
      if (parseFloat(value) < 0) {
        throw new Error('价格不能为负数');
      }
      return true;
    }),
  
  body('isFree')
    .isBoolean()
    .withMessage('免费标识必须是布尔值'),
  
  body('estimatedDuration')
    .optional()
    .isInt({ min: 1 })
    .withMessage('预计学习时长必须是正整数'),
  
  body('tags')
    .optional()
    .isArray()
    .withMessage('标签必须是数组格式'),
  
  body('learningObjectives')
    .optional()
    .isArray()
    .withMessage('学习目标必须是数组格式')
];

const updateCourseValidation = [
  param('id')
    .isUUID()
    .withMessage('课程ID格式无效'),
  
  ...createCourseValidation.map(validation => {
    // 将所有字段设为可选
    if (validation.builder && validation.builder.fields) {
      validation.builder.fields.forEach(field => {
        if (field !== 'id') {
          validation.optional();
        }
      });
    }
    return validation;
  })
];

const getCoursesValidation = [
  query('page')
    .optional()
    .isInt({ min: 1 })
    .withMessage('页码必须是正整数'),
  
  query('limit')
    .optional()
    .isInt({ min: 1, max: 100 })
    .withMessage('每页数量必须在1-100之间'),
  
  query('level')
    .optional()
    .isIn(['beginner', 'intermediate', 'advanced', 'expert'])
    .withMessage('难度级别无效'),
  
  query('status')
    .optional()
    .isIn(['draft', 'published', 'archived'])
    .withMessage('状态值无效'),
  
  query('isFree')
    .optional()
    .isBoolean()
    .withMessage('免费标识必须是布尔值'),
  
  query('search')
    .optional()
    .isLength({ min: 1, max: 100 })
    .withMessage('搜索关键词长度必须在1-100个字符之间'),
  
  query('sortBy')
    .optional()
    .isIn(['createdAt', 'publishedAt', 'title', 'enrollmentCount', 'averageRating'])
    .withMessage('排序字段无效'),
  
  query('sortOrder')
    .optional()
    .isIn(['ASC', 'DESC'])
    .withMessage('排序方向无效')
];

// 工具函数
const handleValidationErrors = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const errorMessages = errors.array().map(error => error.msg);
    throw new ValidationError('验证失败', errorMessages);
  }
  next();
};

const buildCourseQuery = (queryParams) => {
  const { level, status, isFree, search, teacherId, categoryId } = queryParams;
  const where = {};
  
  if (level) {
    where.level = level;
  }
  
  if (status) {
    where.status = status;
  } else {
    // 默认只显示已发布的课程（对于公开接口）
    where.status = 'published';
  }
  
  if (isFree !== undefined) {
    where.isFree = isFree === 'true';
  }
  
  if (teacherId) {
    where.teacherId = teacherId;
  }
  
  if (categoryId) {
    where.categoryId = categoryId;
  }
  
  if (search) {
    const { Op } = require('sequelize');
    where[Op.or] = [
      { title: { [Op.like]: `%${search}%` } },
      { subtitle: { [Op.like]: `%${search}%` } },
      { description: { [Op.like]: `%${search}%` } }
    ];
  }
  
  return where;
};

const checkCourseOwnership = async (req, res, next) => {
  try {
    const { id } = req.params;
    const currentUser = req.user;
    
    const course = await Course.findByPk(id);
    if (!course) {
      throw new AppError('课程不存在', 404);
    }
    
    // 检查权限：课程创建者或管理员可以操作
    if (course.teacherId !== currentUser.id && !['admin', 'super_admin'].includes(currentUser.role)) {
      throw new AppError('无权限操作此课程', 403);
    }
    
    req.course = course;
    next();
  } catch (error) {
    next(error);
  }
};

// 路由处理函数

/**
 * @route   GET /api/courses
 * @desc    获取课程列表
 * @access  Public
 */
router.get('/', getCoursesValidation, handleValidationErrors, async (req, res, next) => {
  try {
    const {
      page = 1,
      limit = 20,
      sortBy = 'publishedAt',
      sortOrder = 'DESC'
    } = req.query;
    
    const offset = (page - 1) * limit;
    const where = buildCourseQuery(req.query);
    
    const { count, rows: courses } = await Course.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'realName', 'avatar']
        }
      ],
      limit: parseInt(limit),
      offset,
      order: [[sortBy, sortOrder.toUpperCase()]]
    });
    
    const totalPages = Math.ceil(count / limit);
    
    res.json({
      success: true,
      data: {
        courses,
        pagination: {
          currentPage: parseInt(page),
          totalPages,
          totalItems: count,
          itemsPerPage: parseInt(limit),
          hasNextPage: page < totalPages,
          hasPrevPage: page > 1
        }
      }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   GET /api/courses/popular
 * @desc    获取热门课程
 * @access  Public
 */
router.get('/popular', query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('数量限制必须在1-50之间'), handleValidationErrors, async (req, res, next) => {
  try {
    const { limit = 10 } = req.query;
    
    const courses = await Course.getPopular(parseInt(limit));
    
    res.json({
      success: true,
      data: { courses }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   GET /api/courses/latest
 * @desc    获取最新课程
 * @access  Public
 */
router.get('/latest', query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('数量限制必须在1-50之间'), handleValidationErrors, async (req, res, next) => {
  try {
    const { limit = 10 } = req.query;
    
    const courses = await Course.getLatest(parseInt(limit));
    
    res.json({
      success: true,
      data: { courses }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   GET /api/courses/free
 * @desc    获取免费课程
 * @access  Public
 */
router.get('/free', getCoursesValidation, handleValidationErrors, async (req, res, next) => {
  try {
    const {
      page = 1,
      limit = 20,
      sortBy = 'publishedAt',
      sortOrder = 'DESC'
    } = req.query;
    
    const offset = (page - 1) * limit;
    
    const { count, rows: courses } = await Course.getFree({
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'realName', 'avatar']
        }
      ],
      limit: parseInt(limit),
      offset,
      order: [[sortBy, sortOrder.toUpperCase()]]
    });
    
    const totalPages = Math.ceil(count / limit);
    
    res.json({
      success: true,
      data: {
        courses,
        pagination: {
          currentPage: parseInt(page),
          totalPages,
          totalItems: count,
          itemsPerPage: parseInt(limit),
          hasNextPage: page < totalPages,
          hasPrevPage: page > 1
        }
      }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   GET /api/courses/search
 * @desc    搜索课程
 * @access  Public
 */
router.get('/search', query('q').notEmpty().withMessage('搜索关键词不能为空'), getCoursesValidation, handleValidationErrors, async (req, res, next) => {
  try {
    const {
      q: keyword,
      page = 1,
      limit = 20,
      sortBy = 'publishedAt',
      sortOrder = 'DESC'
    } = req.query;
    
    const offset = (page - 1) * limit;
    
    const { count, rows: courses } = await Course.search(keyword, {
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'realName', 'avatar']
        }
      ],
      limit: parseInt(limit),
      offset,
      order: [[sortBy, sortOrder.toUpperCase()]]
    });
    
    const totalPages = Math.ceil(count / limit);
    
    res.json({
      success: true,
      data: {
        courses,
        pagination: {
          currentPage: parseInt(page),
          totalPages,
          totalItems: count,
          itemsPerPage: parseInt(limit),
          hasNextPage: page < totalPages,
          hasPrevPage: page > 1
        },
        searchKeyword: keyword
      }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   GET /api/courses/my
 * @desc    获取我的课程（教师）
 * @access  Private (Teacher/Admin)
 */
router.get('/my', authenticate, authorize(['teacher', 'admin', 'super_admin']), getCoursesValidation, handleValidationErrors, async (req, res, next) => {
  try {
    const {
      page = 1,
      limit = 20,
      sortBy = 'createdAt',
      sortOrder = 'DESC'
    } = req.query;
    
    const offset = (page - 1) * limit;
    const where = buildCourseQuery({ ...req.query, teacherId: req.user.id });
    
    // 移除默认的状态过滤，显示所有状态的课程
    delete where.status;
    if (req.query.status) {
      where.status = req.query.status;
    }
    
    const { count, rows: courses } = await Course.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset,
      order: [[sortBy, sortOrder.toUpperCase()]]
    });
    
    const totalPages = Math.ceil(count / limit);
    
    res.json({
      success: true,
      data: {
        courses,
        pagination: {
          currentPage: parseInt(page),
          totalPages,
          totalItems: count,
          itemsPerPage: parseInt(limit),
          hasNextPage: page < totalPages,
          hasPrevPage: page > 1
        }
      }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   GET /api/courses/:id
 * @desc    获取课程详情
 * @access  Public
 */
router.get('/:id', param('id').isUUID().withMessage('课程ID格式无效'), handleValidationErrors, async (req, res, next) => {
  try {
    const { id } = req.params;
    
    const course = await Course.findByPk(id, {
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'realName', 'avatar', 'bio']
        }
      ]
    });
    
    if (!course) {
      throw new AppError('课程不存在', 404);
    }
    
    // 增加浏览次数
    await course.incrementViewCount();
    
    res.json({
      success: true,
      data: { course }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   POST /api/courses
 * @desc    创建课程
 * @access  Private (Teacher/Admin)
 */
router.post('/', authenticate, authorize(['teacher', 'admin', 'super_admin']), createCourseValidation, handleValidationErrors, async (req, res, next) => {
  try {
    const courseData = {
      ...req.body,
      teacherId: req.user.id
    };
    
    const course = await Course.create(courseData);
    
    logger.request('课程创建', {
      courseId: course.id,
      title: course.title,
      teacherId: course.teacherId,
      ip: req.ip
    });
    
    res.status(201).json({
      success: true,
      message: '课程创建成功',
      data: { course }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   PUT /api/courses/:id
 * @desc    更新课程
 * @access  Private (Course Owner/Admin)
 */
router.put('/:id', authenticate, updateCourseValidation, handleValidationErrors, checkCourseOwnership, async (req, res, next) => {
  try {
    const course = req.course;
    
    await course.update(req.body);
    
    logger.request('课程更新', {
      courseId: course.id,
      updatedBy: req.user.id,
      changes: Object.keys(req.body),
      ip: req.ip
    });
    
    res.json({
      success: true,
      message: '课程更新成功',
      data: { course }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   DELETE /api/courses/:id
 * @desc    删除课程
 * @access  Private (Course Owner/Admin)
 */
router.delete('/:id', authenticate, param('id').isUUID().withMessage('课程ID格式无效'), handleValidationErrors, checkCourseOwnership, async (req, res, next) => {
  try {
    const course = req.course;
    
    // 软删除
    await course.destroy();
    
    logger.request('课程删除', {
      courseId: course.id,
      title: course.title,
      deletedBy: req.user.id,
      ip: req.ip
    });
    
    res.json({
      success: true,
      message: '课程删除成功'
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   POST /api/courses/:id/publish
 * @desc    发布课程
 * @access  Private (Course Owner/Admin)
 */
router.post('/:id/publish', authenticate, param('id').isUUID().withMessage('课程ID格式无效'), handleValidationErrors, checkCourseOwnership, async (req, res, next) => {
  try {
    const course = req.course;
    
    if (course.status === 'published') {
      throw new AppError('课程已发布', 400);
    }
    
    await course.publish();
    
    logger.request('课程发布', {
      courseId: course.id,
      title: course.title,
      publishedBy: req.user.id,
      ip: req.ip
    });
    
    res.json({
      success: true,
      message: '课程发布成功',
      data: { course }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   POST /api/courses/:id/archive
 * @desc    归档课程
 * @access  Private (Course Owner/Admin)
 */
router.post('/:id/archive', authenticate, param('id').isUUID().withMessage('课程ID格式无效'), handleValidationErrors, checkCourseOwnership, async (req, res, next) => {
  try {
    const course = req.course;
    
    if (course.status === 'archived') {
      throw new AppError('课程已归档', 400);
    }
    
    await course.archive();
    
    logger.request('课程归档', {
      courseId: course.id,
      title: course.title,
      archivedBy: req.user.id,
      ip: req.ip
    });
    
    res.json({
      success: true,
      message: '课程归档成功',
      data: { course }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   POST /api/courses/:id/upload-cover
 * @desc    上传课程封面
 * @access  Private (Course Owner/Admin)
 */
router.post('/:id/upload-cover', authenticate, param('id').isUUID().withMessage('课程ID格式无效'), handleValidationErrors, checkCourseOwnership, upload.single('coverImage'), async (req, res, next) => {
  try {
    const course = req.course;
    
    if (!req.file) {
      throw new AppError('请选择要上传的封面图片', 400);
    }
    
    const coverImageUrl = `/uploads/courses/covers/${req.file.filename}`;
    
    await course.update({ coverImage: coverImageUrl });
    
    logger.request('课程封面上传', {
      courseId: course.id,
      coverImageUrl,
      uploadedBy: req.user.id,
      ip: req.ip
    });
    
    res.json({
      success: true,
      message: '封面上传成功',
      data: {
        coverImage: coverImageUrl
      }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   POST /api/courses/:id/upload-attachments
 * @desc    上传课程附件
 * @access  Private (Course Owner/Admin)
 */
router.post('/:id/upload-attachments', authenticate, param('id').isUUID().withMessage('课程ID格式无效'), handleValidationErrors, checkCourseOwnership, upload.array('attachments', 5), async (req, res, next) => {
  try {
    const course = req.course;
    
    if (!req.files || req.files.length === 0) {
      throw new AppError('请选择要上传的附件', 400);
    }
    
    const attachments = req.files.map(file => ({
      name: file.originalname,
      url: `/uploads/courses/attachments/${file.filename}`,
      size: file.size,
      type: file.mimetype
    }));
    
    // 合并现有附件
    const existingAttachments = course.attachments || [];
    const updatedAttachments = [...existingAttachments, ...attachments];
    
    await course.update({ attachments: updatedAttachments });
    
    logger.request('课程附件上传', {
      courseId: course.id,
      attachmentCount: attachments.length,
      uploadedBy: req.user.id,
      ip: req.ip
    });
    
    res.json({
      success: true,
      message: '附件上传成功',
      data: {
        attachments: updatedAttachments
      }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   GET /api/courses/:id/statistics
 * @desc    获取课程统计信息
 * @access  Private (Course Owner/Admin)
 */
router.get('/:id/statistics', authenticate, param('id').isUUID().withMessage('课程ID格式无效'), handleValidationErrors, checkCourseOwnership, async (req, res, next) => {
  try {
    const course = req.course;
    
    const statistics = course.getStatistics();
    
    res.json({
      success: true,
      data: { statistics }
    });
  } catch (error) {
    next(error);
  }
});

module.exports = router;